<template>
  <div class="login-container">
    <el-card class="login-card">
      <div class="login-header">
        <h2 class="login-title">欢迎登录游客服务系统</h2>
      </div>
      <el-form
          ref="loginFormRef"
          style="max-width: 600px"
          :model="loginForm"
          status-icon
          :rules="rules"
          label-width="auto"
          class="demo-ruleForm"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="loginForm.username" clearable autocomplete="off" :prefix-icon="User"/>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="loginForm.password" clearable type="password" show-password autocomplete="off" :prefix-icon="InfoFilled"/>
        </el-form-item>
        <el-form-item>
          <el-button class="login-btn" type="primary" @click="submitForm()">
            登录
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { ElMessage } from 'element-plus';
import service from "@/util/request.js";
import { setStorage } from "@/util/localStorage.js";
import Router from "@/router";

const loginForm = ref({
  username: '',
  password: ''
});

const rules = ref({
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
});

const submitForm = () => {
  loginFormRef.value.validate((valid) => {
    if (valid) {
      login();
    } else {
      ElMessage.error("请按照规则输入用户名或密码");
    }
  });
};

const loginFormRef = ref(null);

const login = () => {
  service.post("/login", loginForm.value)
      .then((res) => {
        if (res && res.code === 200) {
          setStorage("Token", res.datas.token);
          ElMessage.success("登录成功");
          Router.push("/complaint");
        } else {
          ElMessage.error(res && res.message ? res.message : "登录失败"); // 使用三元表达式处理未定义的情况
        }
      })
      .catch((error) => {
        console.error('登录失败', error);
        ElMessage.error('登录失败，请稍后再试');
      });
};
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background: linear-gradient(to right, rgba(30, 87, 153, 0.99), #2987d5, #80bdee);
}

.login-card {
  width: 600px;
  padding: 40px;
  border-radius: 20px;
  box-shadow: 0 4px 8px rgb(0,0,0,0.1);
  background: #fff;
}

.login-title {
  font-size: 24px;
  font-weight: bold;
  text-align: center;
  margin-bottom: 40px;
}

.login-header {
  margin-bottom: 30px;
}

.login-btn {
  width: 100%;
}
</style>
